# -*- coding:utf-8 -*-

# 1.导入flask扩展
from flask import Flask, send_file, make_response, request, send_from_directory, g 
import pymysql 
import json 
import random 
from time import sleep 

# 食物的位置
food = None

# 一些参数
SCREEN_SIZE = [1000, 1000]
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
LIGHT_GREY = (100,100,100)
BLACK_GREY = (50,50,50)
DEEP_BLUE = (23,61,146)
GREEN = (128,194,105)
SNAKE_COLOR = (66, 114, 244)
FOOD_COLOR = (0, 100, 0)

CELL_RADIUS = 20
CELL_SIZE = 18
FOOD_RADIUS = 18

MSG_POSITION = (SCREEN_SIZE[0]//2-140, SCREEN_SIZE[1]//2)
SCORE_POSITION = (10,10)

# 2.创建flask应用程序实例
# 需要传入__name__,作用是为了确定资源所在的路径
app = Flask(__name__)
# app.config['ENV'] = "development"
app.config['SECRET_KEY']="demo"

# 连接数据库
connect = pymysql.connect(
    host='localhost',
    user='root',
    passwd="",
    charset="utf8",
    autocommit=True,
    database="snake"
)
cur = connect.cursor() # 创建游标，用于读取数据

# 随机生成食物
def generate_food_pos(info):
    global food, CELL_RADIUS, SCREEN_SIZE
    while food is None:
        cell_diameter = CELL_RADIUS * 2
        rand_x = random.randint(1, (SCREEN_SIZE[0]//cell_diameter)-1)* cell_diameter
        rand_y = random.randint(1, (SCREEN_SIZE[1]//cell_diameter)-1)* cell_diameter
        for body in info:
            body = body["position"]
            body = json.loads(body.replace("'", "\""))["body"]
            body = json.loads(body)
            if [rand_x, rand_y] not in body:
                food = (rand_x, rand_y)

# 是否吃掉食物
def is_snake_food_collide(params):
    global food, CELL_RADIUS, SCREEN_SIZE
    body = json.loads(params["body"])
    direction = params['direction']
    head = body[0].copy() # 复制头

    if direction == "U":
        head[1] -= CELL_RADIUS *2
    elif direction == "D":
        head[1] += CELL_RADIUS *2
    elif direction == "L":
        head[0] -= CELL_RADIUS *2
    else:
        head[0] += CELL_RADIUS *2

    if (head[0] == food[0]) and (head[1] == food[1]):
        body.insert(0, food)
        params["body"] =  json.dumps(body)
        food = None 
    # sleep(5)
    return params


# 3. 定义路由和视图函数
# Flask中定义路由是通过装饰器实现的
@app.route('/',methods=["GET","POST"])
def index():
    """蛇上传位置数据，并下载其他蛇的位置"""
    args = request.args # 获取get参数
    info = {
        "status": 200,
        "data":[],
        "info":"",
        'food':None
    }
    params = {
        'room':args.get("room"),
        'snake':args.get("snake_num"),
        'name':args.get("name"),
        'color':args.get("color"),
        'size':args.get("size"),
        'body':args.get("body"),
        'direction':args.get("direction"),
    }
    if params["name"] == "":
        return ""
    else:
        if food != None:
            params = is_snake_food_collide(params)
        insert_data = json.dumps(params).replace("\"","'")
        # 判断该蛇是否在数据表中
        sql1 = r"select * from position where room_num={};".format(params["room"])
        cur.execute(sql1)
        datas = cur.fetchall()
        snakes = [str(data[2]) for data in datas]
        if params["snake"] in snakes:
            sql2 = r"""UPDATE position SET s_position = "{}" WHERE room_num = {} and snake_num={};""".format(insert_data, params["room"], params["snake"])
            cur.execute(sql2)
        else:
            sql3 = r"""insert into position VALUES("{}", "{}", "{}");""".format(params["room"],insert_data, params["snake"])
            print(sql3)
            cur.execute(sql3)
    sql4 = "select * from position where room_num={};".format(params["room"])
    datas = cur.execute(sql4)
    if datas == 0:
        info["info"] = "获取数据失败"
        info["status"] = 404

        #设置响应头
        resp = make_response(json.dumps(info))
        resp.status = "200"            # 设置状态码
        resp.headers["Content-Type"] = "application/json"      # 设置响应头 
        resp.headers["Access-Control-Allow-Origin"] = "*"      # 设置响应头 
        return resp
    datas = cur.fetchall()
    for data in datas:
        snake = {
            "room_num":data[0],
            "position":data[1],
            "snake_num":data[2],
        }
        info["data"].append(snake)
    
    if food == None:
        generate_food_pos(info["data"])
    info["food"] = food
    #设置响应头
    resp = make_response(json.dumps(info))
    resp.status = "200"            # 设置状态码
    resp.headers["Content-Type"] = "application/json"      # 设置响应头 
    resp.headers["Access-Control-Allow-Origin"] = "*"      # 设置响应头 
    return resp

# 4. 启动服务
if __name__ == '__main__':
    app.run()
